package com.tudouji.project.farepay.service.impl;

import com.flow.service.pojo.BasePojo;
import com.flow.service.pojo.ResultParam;
import com.flow.service.pojo.result.FlowResult;
import com.flow.service.process.service.IFlowBaseService;
import com.github.pagehelper.PageHelper;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.common.utils.sql.SqlUtil;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.page.PageDomain;
import com.tudouji.framework.web.page.TableSupport;
import com.tudouji.project.farepay.domain.FarepayApply;
import com.tudouji.project.farepay.mapper.FarepayApplyMapper;
import com.tudouji.project.farepay.service.IFarepayApplyService;
import com.tudouji.project.flow.utils.FlowProcessUtil;
import com.tudouji.project.organization.domain.Department;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.mapper.DepartmentMapper;
import com.tudouji.project.organization.mapper.OrganizationMapper;
import com.tudouji.project.permission.domain.Salespermission;
import com.tudouji.project.permission.service.impl.SalespermissionServiceImpl;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.domain.Tuser;
import com.tudouji.project.system.domain.Upimage;
import com.tudouji.project.system.mapper.UpimageMapper;
import com.tudouji.project.system.service.ITuserService;
import com.tudouji.project.system.service.impl.BusinesscodeServiceImpl;
import com.tudouji.project.wlinfo.mapper.WlinfoMapper;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.List;

/**
 * 物流运费付款申请Service业务层处理
 *
 * @author tudouji
 * @date 2021-10-27
 */
@Service
public class FarepayApplyServiceImpl implements IFarepayApplyService, IFlowBaseService {
    @Autowired
    private FarepayApplyMapper farepayApplyMapper;
    @Autowired
    private BusinesscodeServiceImpl codeService;
    @Autowired
    private SalespermissionServiceImpl permissionService;
    @Autowired
    private FlowProcessUtil processUtils;
    @Autowired
    private ITuserService tuserService;
    @Autowired
    private UpimageMapper upimageMapper;
    @Autowired
    private WlinfoMapper wlinfoMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private OrganizationMapper organizationMapper;

    /**
     * 查询物流运费付款申请
     *
     * @param guid 物流运费付款申请ID
     * @return 物流运费付款申请
     */
    @Override
    public FarepayApply selectFarepayApplyById(String guid) {
        return farepayApplyMapper.selectFarepayApplyById(guid);
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (com.tudouji.common.utils.StringUtils.isNotNull(pageNum) && com.tudouji.common.utils.StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    /**
     * 查询物流运费付款申请列表
     *
     * @param farepayApply 物流运费付款申请
     * @return 物流运费付款申请
     */
    @Override
    public List<FarepayApply> selectFarepayApplyList(FarepayApply farepayApply, String status, String functionType) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (farepayApply == null) {
            farepayApply = new FarepayApply();
        }
        if (StringUtils.isNotBlank(status)) {
            if (status.equals("00")) {// 待处理
                farepayApply.setCreateBy(sysUser.getUserId());
                startPage();
                return farepayApplyMapper.selectFarepayApplyPendingList(farepayApply);
            } else {
                String[] sts = status.split(",");
                Integer[] stss = (Integer[]) ConvertUtils.convert(sts, Integer.class);
                farepayApply.setStats(stss);
            }
        }
        if (StringUtils.isNotBlank(farepayApply.getStatusStr())) {
            String[] sts = farepayApply.getStatusStr().split(",");
            Integer[] stss = (Integer[]) ConvertUtils.convert(sts, Integer.class);
            farepayApply.setStats(stss);
        }

        String phone = SecurityUtils.getLoginUser().getUser().getPhonenumber();
        Tuser tuser = tuserService.selectTuserByName(phone);
        // 查询是否有全局权限
        List<Salespermission> permissions = permissionService.getPermByScAndFunc(tuser.getGuid(), functionType, "4");
        if (permissions.size() > 0) {
            startPage();
            return farepayApplyMapper.selectFarepayApplyList(farepayApply);
        } else {
            farepayApply.setCreateBy(sysUser.getUserId());
            farepayApply.setOperatorid(tuser.getGuid());
            // 是否有部门权限
            permissions = permissionService.getPermByScAndFunc(tuser.getGuid(), functionType, "2");
            startPage();
            if (permissions.size() > 0) {
                String[] deptids = new String[permissions.size()];
                for (int i = 0; i < permissions.size(); i++) {
                    deptids[i] = permissions.get(i).getDepartid();
                }
                farepayApply.setDepids(deptids);
                return farepayApplyMapper.selectFarepayApplyByDep(farepayApply);
            }
            return farepayApplyMapper.selectFarepayApplyList(farepayApply);
        }
    }
    @Override
    public BigDecimal selectFarepayApplyListAmount(FarepayApply farepayApply, String status, String functionType) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if (farepayApply == null) {
            farepayApply = new FarepayApply();
        }

        String phone = SecurityUtils.getLoginUser().getUser().getPhonenumber();
        Tuser tuser = tuserService.selectTuserByName(phone);
        if (StringUtils.isNotBlank(farepayApply.getStatusStr())) {
            String[] sts = farepayApply.getStatusStr().split(",");
            Integer[] stss = (Integer[]) ConvertUtils.convert(sts, Integer.class);
            farepayApply.setStats(stss);
        }
        // 查询是否有全局权限
        List<Salespermission> permissions = permissionService.getPermByScAndFunc(tuser.getGuid(), functionType, "4");
        if (permissions.size() > 0) {
            return farepayApplyMapper.selectFarepayApplyListAmount(farepayApply);
        } else {
            farepayApply.setCreateBy(sysUser.getUserId());
            farepayApply.setOperatorid(tuser.getGuid());
            // 是否有部门权限
            permissions = permissionService.getPermByScAndFunc(tuser.getGuid(), functionType, "2");
            if (permissions.size() > 0) {
                String[] deptids = new String[permissions.size()];
                for (int i = 0; i < permissions.size(); i++) {
                    deptids[i] = permissions.get(i).getDepartid();
                }
                farepayApply.setDepids(deptids);
                return farepayApplyMapper.selectFarepayApplyByDepAmount(farepayApply);
            }
            return farepayApplyMapper.selectFarepayApplyListAmount(farepayApply);
        }
    }

    /**
     * 新增物流运费付款申请
     *
     * @param farepayApply 物流运费付款申请
     * @return 结果
     */
    @Override
    public AjaxResult insertFarepayApply(FarepayApply farepayApply) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        try {
            String phone = SecurityUtils.getLoginUser().getUser().getPhonenumber();
            Tuser tuser = tuserService.selectTuserByName(phone);
            farepayApply.setStatus(-1);
            farepayApply.setOperatorid(tuser.getGuid());
            farepayApply.setCreateBy(sysUser.getUserId());
            farepayApply.setOperator(tuser.getRealname());
            farepayApply.setCreatetime(DateUtils.getNowDate());
            farepayApply.setCode(codeService.getCode("11"));
            farepayApply.setFlowid("38");
            farepayApply.setTotalamount((farepayApply.getAmount() == null ? BigDecimal.ZERO : farepayApply.getAmount())
                    .add((farepayApply.getOtheramount() == null ? BigDecimal.ZERO : farepayApply.getOtheramount())));
            farepayApply.setAmount(farepayApply.getTotalamount());
//        Supplier cust=supplierService.selectSupplierById(Long.valueOf(farepayApply.getSupplierId()));
//        farepayApply.setBank(cust.getBank());
//        farepayApply.setBankCode(cust.getBankcode());
            /*Salespermission per=new Salespermission();
            per.setUserguid(tuser.getGuid());
            per.setOrgid(farepayApply.getOrgguid());
            per.setPermission(63);
            List<Department> deps=  salespermissionService.getDepsPermisByOrg(per);
            if (deps.size() > 0){
                farepayApply.setDepartid(deps.get(0).getGuid());
                farepayApply.setDepartname(deps.get(0).getName());
            }else{
                return AjaxResult.error("没有运费付款申请发起权限！");
            }*/
            farepayApplyMapper.insertFarepayApply(farepayApply);
            if (StringUtils.isNotBlank(farepayApply.getFileIds())) {
                String[] ids = (String[]) ConvertUtils.convert(farepayApply.getFileIds().split(","), String.class);
                for (String id : ids) {
                    Upimage file = new Upimage();
                    file.setGuid(id);
                    file.setEvidenceguid(String.valueOf(farepayApply.getId()));
                    file.setImagetype("farepay_apply");
                    upimageMapper.updateUpimage(file);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

    /**
     * 修改物流运费付款申请
     *
     * @param farepayApply 物流运费付款申请
     * @return 结果
     */
    @Override
    public int updateFarepayApply(FarepayApply farepayApply) {
        FarepayApply fa = farepayApplyMapper.selectFarepayApplyById(String.valueOf(farepayApply.getId()));
        farepayApply.setTotalamount((fa.getTotalamount() == null ? BigDecimal.ZERO : fa.getTotalamount())
                .subtract(fa.getOtheramount() == null ? BigDecimal.ZERO : fa.getOtheramount())
                .add((farepayApply.getOtheramount() == null ? BigDecimal.ZERO : farepayApply.getOtheramount())));
        farepayApply.setAmount(farepayApply.getTotalamount());
        return farepayApplyMapper.updateFarepayApply(farepayApply);
    }

    /**
     * 批量删除物流运费付款申请
     *
     * @param guids 需要删除的物流运费付款申请ID
     * @return 结果
     */
    @Override
    public int deleteFarepayApplyByIds(String[] guids) {
        return farepayApplyMapper.deleteFarepayApplyByIds(guids);
    }

    /**
     * 删除物流运费付款申请信息
     *
     * @param guid 物流运费付款申请ID
     * @return 结果
     */
    @Override
    public int deleteFarepayApplyById(String guid) {
        return farepayApplyMapper.deleteFarepayApplyById(guid);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult save(Long id, String fileIds, Long taskid, String opinion) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        FarepayApply farepayApply = farepayApplyMapper.selectFarepayApplyById(String.valueOf(id));
        if (null == farepayApply.getTotalamount() || BigDecimal.ZERO.compareTo(farepayApply.getTotalamount()) == 0) {
            return AjaxResult.error("运费支付金额不能为空！");
        }
        Department department = departmentMapper.selectDepartmentById(farepayApply.getDepartid());
        farepayApply.setDeptId(department.getId());
        Organization organization = organizationMapper.selectOrganizationById(farepayApply.getOrgguid());
        farepayApply.setOrgId(organization.getId());
        processUtils.updateTaskByOrderId(id,sysUser,38L);
        FlowResult result = processUtils.defaultStart(processUtils.getStartNode(Long.valueOf(farepayApply.getFlowid())), farepayApply, fileIds, sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            FarepayApply pb = new FarepayApply();
            pb.setStatus(result.getNextStat());
            pb.setId(farepayApply.getId());
            pb.setDeptId(department.getId());
            pb.setOrgId(organization.getId());
            this.farepayApplyMapper.updateFarepayApply(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult pay(Long id, Long taskid, String opinion, String fileIds) {
        //更新物流单支付状态
        wlinfoMapper.updateWlinfoPayStat(id);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        FarepayApply recharge = farepayApplyMapper.selectFarepayApplyById(String.valueOf(id));
        Department department = departmentMapper.selectDepartmentById(recharge.getDepartid());
        recharge.setDeptId(department.getId());
        Organization organization = organizationMapper.selectOrganizationById(recharge.getOrgguid());
        recharge.setOrgId(organization.getId());
        FlowResult result = processUtils.defaultApproval(taskid, fileIds, opinion, recharge
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            FarepayApply pb = new FarepayApply();
            pb.setStatus(result.getNextStat());
            pb.setId(recharge.getId());
            this.farepayApplyMapper.updateFarepayApply(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult approval(Long id, Long taskid, String opinion, String fileIds) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        FarepayApply recharge = farepayApplyMapper.selectFarepayApplyById(String.valueOf(id));

        Department department = departmentMapper.selectDepartmentById(recharge.getDepartid());
        recharge.setDeptId(department.getId());
        Organization organization = organizationMapper.selectOrganizationById(recharge.getOrgguid());
        recharge.setOrgId(organization.getId());
        FlowResult result = processUtils.defaultApproval(taskid, fileIds, opinion, recharge
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            FarepayApply pb = new FarepayApply();
            pb.setStatus(result.getNextStat());
            pb.setId(recharge.getId());
            this.farepayApplyMapper.updateFarepayApply(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult refuse(Long id, String fileIds, String opinion, Long taskid, Long refuseNodeid, Long backUserid) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        FarepayApply recharge = farepayApplyMapper.selectFarepayApplyById(String.valueOf(id));

        Department department = departmentMapper.selectDepartmentById(recharge.getDepartid());
        recharge.setDeptId(department.getId());
        Organization organization = organizationMapper.selectOrganizationById(recharge.getOrgguid());
        recharge.setOrgId(organization.getId());
        FlowResult result = processUtils.defaultRefuse(taskid, fileIds, opinion, recharge
                , sysUser, refuseNodeid, backUserid);

        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            FarepayApply pb = new FarepayApply();
            pb.setStatus(result.getNextStat());
            pb.setId(recharge.getId());
            this.farepayApplyMapper.updateFarepayApply(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult del(Long id) {
        FarepayApply apply = farepayApplyMapper.selectFarepayApplyById(String.valueOf(id));
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        FarepayApply farepayApply = new FarepayApply();
        farepayApply.setId(id);
        farepayApply.setStatus(0);
        farepayApplyMapper.updateFarepayApply(farepayApply);

        wlinfoMapper.updateWlinfoUnPayStat(id);
        //更新待处理任务
        processUtils.updateTaskByOrderId(id, sysUser, Long.valueOf(apply.getFlowid()));
        return AjaxResult.success();
    }

    @Override
    public BasePojo getBaseById(Long id) {
        return farepayApplyMapper.selectFarepayApplyById(String.valueOf(id));
    }

    @Override
    public BasePojo getBaseByCode(String code) {
        return null;
    }
}
